//
//  NSObject+CW.m
//  CWDevelop
//
//  Created by LittoCats on 7/9/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "NSObject+CW.h"
#import <objc/runtime.h>
#import <objc/message.h>

static NSMapTable *kNSObjectMapTable();

@implementation NSObject (CW)

static const char kDQObjectIdKey;
@dynamic _id;
- (NSString *)_id
{
    NSString *idString = objc_getAssociatedObject(self, &kDQObjectIdKey);
    if (!idString) {
        idString = [NSString stringWithFormat:@"%@_%f_%p",self.class,[NSDate timeIntervalSinceReferenceDate], self];
        [self set_id:idString];
    }
    return idString;
}
- (void)set_id:(NSString *)_id
{
    if (!_id) return;
    objc_setAssociatedObject(self, &kDQObjectIdKey, _id, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [kNSObjectMapTable() setObject:self forKey:_id];
}

@end

@implementation NSObject (CWCategory)

+ (id)findInstanceWithId:(NSString *)_id
{
    return [kNSObjectMapTable() objectForKey:_id];
}

- (BOOL)isEmpty
{
    return self ? [self isMemberOfClass:[NSNull class]] ? YES : NO : YES;
}

@end

#pragma mark- private c function
static NSMapTable *kNSObjectMapTable(){
    static NSMapTable *mapTable = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mapTable = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsWeakMemory valueOptions:NSPointerFunctionsWeakMemory capacity:64];
    });
    return mapTable;
}